function M = playStack(matpath,p,dim_mode,binary,framerate)
%% playStack.m
%M = playStack(matpath,p,dim_mode,binary,framerate)
%INPUTS:
%matpath points to matfile for image stack w/ metadata
%p is position to play (Default=1)
%framerate in frames/second (Default=15)
%OUTPUTS: movie M for conversion to video if needed
%NOTES:
%channel name parsing: 1=BF (or dic,phase), 2=R, 3=G (or Y/citrine), 4=B (or cerulean)
%By default, does not display BF channel for binaries (logicals)

%% Default Arguments
if nargin<1 || ~isstr(matpath)
    [file,path] = uigetfile();
    matpath = [path file];
end
if nargin<2 || isempty(p)
    p=1;
end
if nargin<3 || isempty(dim_mode)
    dim_mode=2;
end
if nargin<4 || isempty(binary)
    binary=true;
end
if nargin<5 || isempty(framerate)
    framerate=15;
end

m = matfile(matpath,'Writable',false);
s = m.s;

if ~binary
    I_p = cell2mat(m.I(p,1));
end

if ndims(squeeze(cell2mat(m.BW(2,1))))==3
    %% 2D RGB in Time or 3D stepping through stack at 1 time point
    play_dim = size(squeeze(cell2mat(m.BW(2,1))),3);
    
    %% Channels to RGB
    
    rgb = zeros(512,512,3,play_dim);
    for c=1:s.channels
        if s.channel_name_std(c)=='W'
            if binary
                continue;
            else
                I_cp = I_p(:,:,:,:,c);
            end
            %BF/Phase/DIC
            for rgb_channel=1:3
                rgb(:,:,rgb_channel,:) = rgb(:,:,rgb_channel,:) + reshape(mat2gray(I_cp),[s.x s.y 1 play_dim]);
            end
        elseif s.channel_num_std(c)>1
            %Fluorescence, 2=R, 3=G, 4=B
            if binary
                I_cp = cell2mat(m.BW(c,p));
            else
                I_cp = I_p(:,:,:,:,c);
            end
            rgb(:,:,s.channel_num_std(c)-1,:) = rgb(:,:,s.channel_num_std(c)-1,:) + reshape(mat2gray(I_cp),[s.x s.y 1 play_dim]);
        end
    end
    clear I_cp
    rgb=rgb/max(rgb(:)); %bounds, since each channel can have at most BF=1 and color=1
    
    
    %% Display and Load to Movie
    for t=1:play_dim
        M(t) = im2frame(squeeze(rgb(:,:,:,t)));
    end
    
    imshow(rgb(:,:,:,1));
    movie(M,1,framerate,[0 0 0 0]);
    
elseif dim_mode==3 && ndims(squeeze(cell2mat(m.BW(2,1))))==4
    %% 3D - colored isosurface: binary only
    if ~binary
        'For XYZ data, input must be binary.'
        return
    end
    %Fluorescence, 2=R, 3=G, 4=B
    rgb_char = 'wrgb';
    for c=1:s.channels
        %Ignore BF/Phase/DIC
        if s.channel_num_std(c) ~= 1
            BW_cp = cell2mat(m.BW(c,p));
            for t=1:s.time
                fig = figure();
                hold on
                isoBinary3(BW_cp(:,:,:,t),[],s,0,rgb_char(s.channel_num_std(c)),.5);
            end
        end
        M(t) = getframe();
        close(fig)
    end
    clear BW_cp
    movie(M,1,framerate,[0 0 0 0]);
else
    'First input is not a matfile with time, z, or z-time stack'
    return
end

end